package com.lap.auth.application.api;

import com.lap.auth.application.api.assembler.ApiAssembler;
import com.lap.auth.application.api.command.CreateApiCmd;
import com.lap.auth.application.api.dto.ApiTreeDto;
import com.lap.auth.domain.api.Api;
import com.lap.auth.domain.api.repository.ApiRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class ApiAppService {

  private final ApiAssembler apiAssembler;
  private final ApiRepository apiRepository;

  public List<ApiTreeDto> queryApiTree() {
    List<Api> allList = apiRepository.findList();
    List<ApiTreeDto> list = apiAssembler.toDtoList(allList);
    return apiAssembler.convertTree(list);
  }

  @Transactional(rollbackFor = Exception.class)
  public void createApis(String module, List<CreateApiCmd> cmdList) {
    List<Api> list = apiAssembler.toDomains(cmdList);
    apiRepository.deleteByModule(module);
    apiRepository.saveAll(list);
  }
}
